#include "Manager.h"

NonCombatUnitManager::NonCombatUnitManager(StratManager *newManager)
{
	manager = newManager;
	miners = new UnitGroup();
}

// private
struct LeadTime NonCombatUnitManager::getUnitRequestTime(Request unitRequest)
{
	return manager->onUnitTimeQuerry(unitRequest);
}

void NonCombatUnitManager::onStart()
{
	minerRequestSent = false;
	supplyRequestSent = false;
	miners->addAction(&MineAction(), this, 0);
}

void NonCombatUnitManager::onStop()
{
}

void NonCombatUnitManager::onTaskCompleted(UnitGroup* group)
{
	group->stop();
}

void NonCombatUnitManager::onThink()
{
	miners->think();

	// Keep the miner group at this minimum value
	int const minerCount = 7;
	if(miners->getCount() < minerCount && !minerRequestSent) {
		Request request;
		request.uType = Broodwar->self()->getRace().getWorker();
		request.group = miners;
		request.count = minerCount - miners->getCount();
		request.priority = 0;

		minersLeft = request.count;
		requestUnits(request);
		minerRequestSent = true;
	}

	// Keep adequite supply maybe ask StratManager about poulation growth rate
	if(Broodwar->self()->supplyTotal() - Broodwar->self()->supplyUsed() <= 16 &&
		!supplyRequestSent) {
			Request request;
			request.uType = Broodwar->self()->getRace().getSupplyProvider();
			request.group = NULL; // must be NULL if not classified.
			request.count = 1;
			request.priority = 1; // only 1 worker can be taken for this task.
			// Determine where to build the building.
			request.position = Broodwar->self()->getStartLocation();

			//requestUnits(request);
			supplyRequestSent = true;
	}
}

// public
bool NonCombatUnitManager::canTransferUnits(Request unitRequest)
{
	return false;
}

// Dispatch request to the workers to build a building
void NonCombatUnitManager::buildUnits(Request unitRequest)
{
	BuildAction buildAction;
	for(int i = 0; i < unitRequest.count; i++)
		buildAction.addBuildingRequest(PUnitType(unitRequest.uType, unitRequest.group,
		unitRequest.priority, unitRequest.position));
	miners->addAction(&buildAction, this, unitRequest.priority);
}

// Classify unit into a group. Do not classify the unit if
// it was requested.
void NonCombatUnitManager::onUnitRecieved(Unit *unit, bool requested)
{
	UnitType uType = unit->getType();
	if(!requested) {
		if(uType.isWorker())
			miners->addUnit(unit);
	}
	else {
		if(minerRequestSent && uType.isWorker())
			if(!--minersLeft)
				minerRequestSent = false;
		else if(supplyRequestSent && uType.supplyProvided())
			supplyRequestSent = false;
	}
}

NonCombatUnitManager::~NonCombatUnitManager()
{
	delete miners;
}